/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.logging.appender.async;

import com.aduib.boot.common.disruptor.Disruptors;
import com.aduib.boot.common.disruptor.ElementEventHandler;
import com.aduib.boot.logging.appender.LogAppender;
import com.aduib.boot.logging.appender.LogUnAsyncAppenderBase;

import java.util.List;
import java.util.Objects;

/**
 * @description: LogAsyncAppenderBase
 * @author: zzh
 * @date: 2021/9/18 09:40
 */
public abstract class LogAsyncAppenderBase<T> extends LogUnAsyncAppenderBase<T> {

  private final Disruptors<T> disruptors;

  public LogAsyncAppenderBase() {
    this.disruptors= Disruptors.<T>builder();
    disruptors.addDefaultEventHandler(new LogEventAsyncHandler());
    disruptors.createAllOne();
  }

  public LogAsyncAppenderBase(Disruptors<T> disruptors) {
    this.disruptors = disruptors;
  }


  @Override
  public List<LogAppender<T>> getLogAppenders() {
    return super.getLogAppenders();
  }

  private class LogEventAsyncHandler extends ElementEventHandler<T> {

    @Override
    public void handleEvent(T t, long sequence, boolean endOfBatch) {
      if (Objects.nonNull(getLogAppenders())){
        for (LogAppender<T> logAppender : getLogAppenders()) {
          logAppender.saveLog(t);
        }
      }
    }
  }
}
